import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token.js';
import route from '@/router'
//定制请求的实例
//导入axios  npm install axios
import axios from 'axios';

export const baseUrl = 'http://192.168.31.63:8081/';

//定义一个变量,记录公共的前缀  ,  baseURL
const instance = axios.create({
    baseURL: baseUrl,
    timeout: 40000,
});

//添加请求拦截器
instance.interceptors.request.use(
    (config)=>{
        //请求前回调
        const tokenStore=useTokenStore();
        if(tokenStore.token){
            config.headers.Authorization=tokenStore.token
        }
        return config
    },
    (err)=>{
        //请求错误回调
        Promise.reject(err)
    }
)
//添加响应拦截器
instance.interceptors.response.use(
    result=>{
        //判断业务状态码
        if(result.data.code===0){
            return result.data;
        }

        //失败
        ElMessage.error(result.data.msg? result.data.msg:"服务异常");
        //异步的状态转化成失败的状态
        return Promise.reject(err);
    },
    err=>{
        if(err.response.status===401){
            ElMessage.error({
                message:err.response.data.message ,
                type:"error",
                grouping:true
            });
            const tokenStore=useTokenStore();
            tokenStore.removeToken();
            route.push("/");
        }else{
            ElMessage.error("服务异常");
        }
    }
)

export default instance;